/*
 * File:   client.c
 * Author: onteria_
 *
 * Created on May 1, 2011, 1:01 PM
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h> 
#include <signal.h>
#include <stdio.h>

#include <miko/defines.h>
#include <miko/protocol.h>
#include <miko/miko.h>
#include <miko/socket.h>
#include <unicode/ustdio.h>

#include "client.h"

void check_socket_error(int error_code, int file_descriptor) {
	const char * error_message = miko_get_error_string(error_code);
	fprintf(stderr, "ERROR %s\n", error_message);
    close(file_descriptor);
}

void prompt_for_data(UFILE *input, const char * prompt, UChar *dest) {
	printf("%s", prompt);
	u_fscanf(input, "%S", dest);
}

int main(int argc, char *argv[])
{
    long bytes_read;
    long bytes_sent;
    int response_code;
    char message[MIKO_MSG_LENGTH];

	struct sockaddr_in6 server_socket;
	struct Miko test;
	UFILE *in;

    signal(SIGINT, cleanup);      /* now handle SIGTERM and SIGINT */    
    signal(SIGTERM, cleanup);
    
    bzero(&test, sizeof(struct Miko));
    in = u_finit(stdin, NULL, NULL);
    prompt_for_data(in, "Enter Miko First Name: ", &test.firstName);
    prompt_for_data(in, "Enter Miko Last Name: ", &test.lastName);
    prompt_for_data(in, "Enter Miko Shrine: ", &test.shrine);
    u_fclose(in);

    connection = socket(AF_INET6, SOCK_STREAM, 0);
    if (connection < 0) {
        perror("ERROR opening socket ");
        return MIKO_ERROR;
    }
    
    /* Part of libmiko, returns NULL if a socket can't be created */
    server_socket = miko_create_socket6(SERVER_PORT, SERVER_HOST);
    if(server_socket.sin6_port == 0) {
        fprintf(stderr, "ERROR failed to create server connection socket\n");
        return -1;
    }
    server_socket.sin6_len = sizeof(server_socket);
    
    if (connect(connection,(struct sockaddr *) &server_socket,sizeof(server_socket)) < 0) {
        perror("ERROR connecting");
    }

    bytes_sent = send_miko_data(connection, &test);
    if(bytes_sent < 0) {
    	check_socket_error(bytes_sent, connection);
    	return MIKO_ERROR;
    }

    bzero(message, sizeof(char) * MIKO_MSG_LENGTH);
    response_code = 0;

    bytes_read = miko_read_server_response(connection, 30, &response_code, message);
    if(bytes_read < 0) {
    	check_socket_error(bytes_read, connection);
    	return MIKO_ERROR;
    }
    printf("[%d] %s\n", response_code, message);

    close(connection);
    return MIKO_SUCCESS;
}
